package com.distributer.policy.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import com.alibaba.fastjson.JSONObject;
import com.distributer.policy.mapper.InsurancePolicyMapper;
import com.distributer.policy.model.InsurancePolicy;
import com.distributer.policy.service.InsurancePolicyService;

@Service
public class InsurancePolicyServiceImpl implements InsurancePolicyService {

	@Autowired
	private InsurancePolicyMapper insurancePolicyMapper;
	@Autowired
	private JedisPool jedisPool;

	public void addPolicy(InsurancePolicy insurancePolicy) {
		insurancePolicyMapper.insert(insurancePolicy);
	}

	public void updatePolicy(InsurancePolicy insurancePolicy) {
		insurancePolicyMapper.update(insurancePolicy);
	}

	public InsurancePolicy getPolicyByJbPolicyNo(String jbPolicyNo) {
		return insurancePolicyMapper.selectInsurancePolicyByJbPolicyNo(jbPolicyNo);
	}

	public void removePolicyFromCacheByJbPolicyNo(String jbPolicyNo) {
		Jedis jedis = jedisPool.getResource();
		try {
			jedis.del(jbPolicyNo);
		} finally {
			jedis.close();
		}
	}

	public void refreshInsrancePolicyCache(InsurancePolicy insurancePolicy) {
		Jedis jedis = jedisPool.getResource();
		try {
			jedis.set(insurancePolicy.getJbPolicyNo(), JSONObject.toJSONString(insurancePolicy));
		} finally {
			jedis.close();
		}
	}

	public InsurancePolicy findInrancePolicyFromCacheByJbPolicyNo(String jbPolicyNo) {
		InsurancePolicy insurancePolicyFromCache = null;
		Jedis jedis = jedisPool.getResource();
		try {
			String cacheSource = jedis.get(jbPolicyNo);
			if (cacheSource != null && !cacheSource.equals("")) {
				insurancePolicyFromCache = JSONObject.parseObject(cacheSource, InsurancePolicy.class);
			}
		} finally {
			jedis.close();
		}
		return insurancePolicyFromCache;
	}

}
